<template>
  <el-dialog
    title="自定义模板下载"
    v-model="showDialogFlag"
    :show-close="true"
    append-to-body
    width="830px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
  >
    <el-form>
      <!-- <el-form-item label="导出数据范围：">
        <el-radio-group v-model="exportRange">
          <el-radio :value="0">导出全部行数据</el-radio>
          <el-radio :value="1">导出筛选行数据</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="导出字段设置：" label-position="top" required>
        <el-transfer
          class="excel-header-transfer"
          ref="transfer"
          v-model="selectData"
          :titles="['可选表头', '已选表头']"
          filterable
          item-class="custom-class"
          filter-placeholder="请输入关键词"
          :data="transferData"
          @change="onChange"
        >
        <template #default="{ option }">
          <div class="trnsfer-label-box">
            <div class="trnsfer-label-box-label">
              <el-tooltip effect="light" :content="option.label">
                <span><span v-if="option.required" class="required-icon">*</span><span>{{ filterSpecialCharByLabel(option.label) }}</span></span>
              </el-tooltip>
            </div>
            <el-icon class="rank-icon"><Rank /></el-icon>
          </div>
        </template>
        </el-transfer>
      </el-form-item>
      <el-form-item v-if="!subFormId" label="唯一标识：" :required="uniqueFiledIdsRequired">
        <el-select v-model="uniqueFiledIds" multiple>
          <el-option v-for="item in uniqueFileds" :key="item.fieldId"  :value="item.fieldId" :label="item.fieldTitle"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showDialogFlag = false">关闭</el-button>
        <el-button type="primary" @click="onOk" :disabled="disabledConFirmBtn" :loading="confirmLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import Sortable from 'sortablejs';
import { saveAs } from 'file-saver'
import { getFormListHeader, exportExcelTemplateFile, exportSubExcelTemplateFile } from '@/api/formtemplate/index'
export default {
  props: {
    widget: Object,
    formTemp: Object,
    formId: String,
    bookId: String,
    recordId: String,
    subFormId: String,
    excelFileNameObj: Object,
  },
  data() {
    return {
      showDialogFlag: false,
      confirmLoading: false,
      exportRange: 1, // 导出范围
      formListHeaderSource: [], // 表头数据源
      transferData: [],
      selectData: [],
      uniqueFiledIds: [],
    }
  },
  computed: {
    uniqueFiledIdsRequired() {
      const str = this.selectData.join(',');
      return str.indexOf('subform') !== -1;
    },
    disabledConFirmBtn() {
      return this.selectData.length == 0 ? true : !this.subFormId && this.uniqueFiledIdsRequired && this.uniqueFiledIds.length == 0 ? true : false;
    },
    uniqueFileds() {
      if (this.formListHeaderSource?.main && this.selectData) {
        return this.formListHeaderSource.main.filter(item => this.selectData.includes(item.fieldId));
      }
      return []
    }
  },
  methods: {
    open() {
      const that = this;
      getFormListHeader({
        version: 1,
        formId: this.formId,
        bookId: this.bookId,
        recordId: this.recordId,
        subFormId: this.subFormId,
      }).then(res => {
        if (res.code === 0) {
          this.formListHeaderSource = res.data;
          this.transferData = [...(res.data.main || []), ...res.data.sub.flat(1)].map(item => ({  
            key: item.fieldId, 
            label: item.fieldTitle, 
            type: item.fieldType,
            required: item.required,
            disabled: item.required,
          }));
          this.selectData = this.transferData.filter(item => item.required).map(item => item.key);
        }
      })
      this.showDialogFlag = true;
      this.$nextTick(() => {
        const res = document.getElementsByClassName('el-transfer-panel__list')
        new Sortable(res[1], {
          animation: 150,
          ghostClass: 'el-transfer-panel__item-sortable',
          onEnd: (evt) => {
            // 通过evt.oldIndex和evt.newIndex更新selectData对应数据的位置
            const temp = that.selectData[evt.oldIndex];
            that.selectData.splice(evt.oldIndex, 1);
            that.selectData.splice(evt.newIndex, 0, temp);
          }
        });
      })
    },
    // 过滤特殊字符
    filterSpecialCharByLabel(str) {
      if (typeof str === 'string') return str = str.replaceAll(/<br>/g, '')
      return str
    },
    onChange() {
      this.$nextTick(() => {
        // 给el-transfer右侧面板子元素动态添加自定义类名
        const panelList = document.querySelectorAll('.excel-header-transfer .el-transfer-panel__list')
        const itemList = panelList[1].querySelectorAll('.el-transfer-panel__item')
        if(itemList.length) {
          itemList.forEach(item => {
            item.classList.add('el-transfer-panel__item-sortable')
          })
        }
      })
    },
    
    /**
     * @description: 确认导出操作
     * 当用户点击确认按钮时，此方法会被触发。
     * 根据选择的导出范围，收集需要导出的字段ID，并调用导出Excel模板文件的方法。
     * 如果导出范围为1且未选择任何字段，则会显示警告信息。
     * 导出成功后，会提示用户下载文件，并关闭弹窗。
     * @return {*}
     * @Author: ZJP
     */    
    async onOk() {
      this.confirmLoading = true;
      let exportFiledIds = '';
      const uniqueFiledIds = this.uniqueFiledIds.join(',');
      if (!this.subFormId && this.uniqueFiledIdsRequired && !uniqueFiledIds.length) {
        this.$message.warning('请选择唯一标识字段');
        this.confirmLoading = false;
        return;
      }

      if (this.exportRange == 1) {
        if (this.selectData.length == 0) {
          this.$message.warning('请选择要导出的字段');
          this.confirmLoading = false;
          return;
        }
        exportFiledIds = this.selectData.join(',');
      }
      const importAPI = this.subFormId ? exportSubExcelTemplateFile : exportExcelTemplateFile;
      const res = await importAPI({
        version: 1,
        formId: this.formId,
        bookId: this.bookId,
        recordId: this.recordId,
        subFormId: this.subFormId,
        exportFiledIds,
        uniqueFiledIds
      })
      const excelName = [this.excelFileNameObj.menuName, this.excelFileNameObj.subFormName, this.excelFileNameObj.userName, this.excelFileNameObj.today].filter(item => item).join('-');
      saveAs(res, `${excelName}.xlsx`);
      this.showDialogFlag = false;
      this.confirmLoading = false;
      // this.exportRange = 1 // 导出范围
      this.formListHeaderSource = []; // 表头数据源
      this.transferData = [];
      this.selectData = [];
      this.uniqueFiledIds = [];
    }
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-transfer-panel {
  width: 300px; /* 修改这里的数值来调整宽度 */
  .rank-icon {
    margin-top: 4px;
    margin-left: 8px;
  }
  &:first-child {
    .rank-icon {
      display: none;
    }
  }
  &:last-child {
    .el-transfer-panel__list {
      .el-checkbox {
        margin-right: 15px;
      }
    }
  }
}
.trnsfer-label-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  align-content: center;
  &-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .required-icon {
    color: red;
    margin-right: 4px;
  }
}
</style>